﻿using System;
using System.Globalization;
using System.Web.Mvc;

namespace Dogshow.Web.Utils
{
    public class DecimalModelBinder : DefaultModelBinder
    {
        static CultureInfo s_EnCulture = new CultureInfo("en-US");
        
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            
            if (valueProviderResult.AttemptedValue.Equals("N.aN") ||
                valueProviderResult.AttemptedValue.Equals("NaN") ||
                valueProviderResult.AttemptedValue.Equals("Infini.ty") ||
                valueProviderResult.AttemptedValue.Equals("Infinity") ||
                string.IsNullOrEmpty(valueProviderResult.AttemptedValue))
                return 0m;

            return valueProviderResult == null ? base.BindModel(controllerContext, bindingContext) : Decimal.Parse(valueProviderResult.AttemptedValue, s_EnCulture);
        } 
    }
}